<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>惊蛰的博客 万恶的IEEE_754规范 ，直接让雪花算法全盘崩</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <style>
        @import url('/css/post-card.css');
        @import url('/css/main.css');
        @import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,600;1,400;1,600&family=Roboto+Slab:wght@700&display=swap');
    </style>
    <style>
        body {
            font-family: Montserrat, sans;
        }

        .page-footer {
            color: var(--text-p3);
        }

        .sitemap {
            display: flex;
            justify-content: space-between;
            margin: .5rem 0 2rem;
            display: grid;
            grid-gap: 1rem 1rem;
            grid-auto-flow: column dense;
        }

        .sitemap-group {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
        }

        .sitemap-group>.fs14 {
            margin: .5rem 0;
        }

        .page-footer .sitemap .sitemap-group>a {
            margin: .2rem 0;
            color: var(--text-p3);
        }

        .page-footer .text p {
            margin: 4px 0;
            line-height: 1.2;
        }
    </style>
    <script src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js"></script>
    <script src="/js/index.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/jquery.scrollbar/0.2.9/jquery.scrollbar.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery_lazyload/1.9.7/jquery.lazyload.min.js"></script>
<meta name="generator" content="Hexo 5.4.0"></head>

<body>
    
<div class="l_body">
    <div class="l_main list">
        
<div class="nav-wrap mobile-hidden">
    <nav class="sub post cap header1">
        <a  href="/">最近发布</a>
        <a 
            href="/wiki/">分类</a>
        <a 
            href="/notes/">标签</a>
        <a href="/bibi/">说说</a>

    </nav>
    <div class="post-body-title header2">
        万恶的IEEE_754规范 ，直接让雪花算法全盘崩
    </div>
</div>

<style>
    .sub2 {
        display: flex;
        flex-direction: column;
        position: absolute;
        z-index: 11;
        background:#ffff!important;
        border-radius: 5px;
    }

    .sub2 a{
        display: block;
        margin-left: 0px!important;
        border-radius: 5px;
        margin: 5px 0 3px 0!important;
    }
</style>


<script>
    $(function () {
        //页面初始化的时候，获取滚动条的高度（上次高度）
        var start_height = $(document).scrollTop();
        //获取导航栏的高度(包含 padding 和 border)
        var navigation_height = $('.header1').outerHeight();
        console.log(start_height, navigation_height);
        $(window).scroll(function () {
            //触发滚动事件后，滚动条的高度（本次高度）
            var end_height = $(document).scrollTop();
            console.log(end_height);
            //触发后的高度 与 元素的高度对比
            if (end_height > navigation_height) {
                $('.header1').addClass('hide');
                $('.header2').addClass('hide');
            } else {
                $('.header1').removeClass('hide');
                $('.header2').removeClass('hide');
            }
            //触发后的高度 与 上次触发后的高度 比较
            if (end_height < start_height) {
                $('.header1').removeClass('hide');
                $('.header2').removeClass('hide');
            }
            //再次获取滚动条的高度，用于下次触发事件后的对比
            start_height = $(document).scrollTop();
        });
    });
</script>


        <h2>
            万恶的IEEE_754规范 ，直接让雪花算法全盘崩
        </h2>

        <div class="body-main-content">
            <h5 id="万恶的IEEE-754规范-，直接让雪花算法全盘崩"><a href="#万恶的IEEE-754规范-，直接让雪花算法全盘崩" class="headerlink" title="万恶的IEEE_754规范 ，直接让雪花算法全盘崩"></a>万恶的IEEE_754规范 ，直接让雪花算法全盘崩</h5><span id="more"></span>

<h3 id="1-事情为什么发生？"><a href="#1-事情为什么发生？" class="headerlink" title="1.事情为什么发生？"></a><strong>1.事情为什么发生？</strong></h3><p>事情还要从ID的架构说起，ID在架构师的要求下，我们改成了雪花算法（Snowflake）生成ID</p>
<p>简单的介绍一下雪花算法，SnowFlake算法生成id的结果是一个64bit大小的整数，它的结构如下图：<br><img src="" data-original="https://i.loli.net/2020/12/03/5rqpvnKRfbcWo16.png"></p>
<p><strong>SnowFlake可以保证：</strong></p>
<blockquote>
<ol>
<li>所有生成的id按时间趋势递增</li>
<li>整个分布式系统内不会产生重复id（因为有datacenterId和workerId来做区分）</li>
</ol>
</blockquote>
<p>这样在遇到系统扩容，分库分表，数据迁移的场景下都不会出现太大的问题</p>
<p>大家伙一讨论，都觉得非常合理，就决定一股脑用雪花算法生成主键ID了</p>
<p>例如现在这样：</p>
<blockquote>
<p>527574217068392807<p><br>527574217068392808</p></p>
</blockquote>
<h3 id="2-问题产生"><a href="#2-问题产生" class="headerlink" title="2.问题产生"></a><strong>2.问题产生</strong></h3><p>问题是我们测试发现的，测试发现有些用户查询列表会没有值，我们把测试的ID放到数据库一查询，库内无此数据</p>
<p>后来我们发现后端返回的数据和前端提交上来的数据是不一样的，ID不同</p>
<p><img src="" data-original="https://i.loli.net/2020/12/03/nfhvBQT4djAI9JH.png"></p>
<h3 id="3-问题验证"><a href="#3-问题验证" class="headerlink" title="3.问题验证"></a><strong>3.问题验证</strong></h3><p>也就是说，一个好好的数字：527183991665594368，经过浏览器一翻译，变成了527183991665594400。</p>
<p>我们在浏览器的devtools里面调试一下。</p>
<p><img src="" data-original="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9jdlFiSkRac0tMcnp2TXlsV2RiTXRNM1FXb1dXTzBDOEk3VHd1cmxLQlQ3QU9MWXptUENvY2w0RktBRU5Rc01FaWE2cjJNMmw1dU5UckJ3aWFYSjRLamZ3LzY0MA?x-oss-processimage/format,png"></p>
<h3 id="4-为什么"><a href="#4-为什么" class="headerlink" title="4.为什么"></a><strong>4.为什么</strong></h3><p>这是因为。在JavaScript中，存在两种数字。Number和BigInt。最常用的，就是number。</p>
<p>最大的Number，叫做<code>Number.MAX_SAFE_INTEGER</code>，它的值为：</p>
<ul>
<li><p> 2^53-1 或者</p>
</li>
<li><p> +/- 9,007,199,254,740,991</p>
</li>
</ul>
<p>众所周知，Java中的Long，是64位的。Js中的这个安全Integer，完全达不到Java中定义的长度。</p>
<p>这就是万恶的<code>IEEE_754规范</code>，它在Long长度大于17位时会出现精度丢失的问题。</p>
<p>在最新的TypeScript3.2中，可是直接使用BigInt这个类型进行编码，或者使用long.js这种封装后的苦，但还是太麻烦了，需要编码太多，而且还可能漏掉。</p>
<p>使用数字类型，传输数据，实在是不太靠谱，转来转去，就物是人非了。</p>
<p>最好的方式，就是使用<code>string</code>进行传递。哪怕以后后台ID的长度变成了128位的，也不惧怕这种转换。</p>
<h2 id="5-End"><a href="#5-End" class="headerlink" title="5.End"></a>5.End</h2><h2 id="这问题，明显不是后端的锅。后端传递了正确的数据到前端，能不能处理、处理的正确不正确，根本和后端一点关系都没有"><a href="#这问题，明显不是后端的锅。后端传递了正确的数据到前端，能不能处理、处理的正确不正确，根本和后端一点关系都没有" class="headerlink" title="这问题，明显不是后端的锅。后端传递了正确的数据到前端，能不能处理、处理的正确不正确，根本和后端一点关系都没有"></a>这问题，明显不是后端的锅。后端传递了正确的数据到前端，能不能处理、处理的正确不正确，根本和后端一点关系都没有</h2><p><strong>能力越强，责任越大。</strong></p>
<p><strong>实事求是，严谨细致。</strong></p>

        </div>
        <div class="page-footer reveal fs12">
    <hr>
    <div class="sitemap">
        <div class="sitemap-group">
            <span class="fs14">博客</span>
            <a href="/">近期发布</a>
            <a href="/wiki/">分类</a>
            <a href="/notes/">标签</a>
            <a href="/archives/">归档</a>
        </div>
        <div class="sitemap-group">
            <span class="fs14">社交</span>
            <a target="_blank" rel="external nofollow noopener noreferrer" href="">GitHub</a>
            <a target="_blank" rel="external nofollow noopener noreferrer" href="">GitLab</a>
        </div>
        <div class="sitemap-group">
            <span class="fs14">更多</span>
            <a href="/about/">关于本站</a>
            <a href="/bibi/">哔哔</a>
            <a target="_blank" rel="external nofollow noopener noreferrer" href="https://image.jingzhe.xyz">图床</a>
        </div>
    </div>
    <div class="text">
        <p>本博客所有文章除特别声明外，均采用
            <a target="_blank" rel="external nofollow noopener noreferrer"
                href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
                CCBY-NC-SA 4.0
            </a>
            许可协议，转载请注明出处。
        </p>
    </div>
</div>
    </div>
    <aside class="l_right">
        
<header class="header">
    <div class="logo-wrap">
        <a class="avatar" href="/about/">
            <img class="avatar" src="" data-original="https://ae01.alicdn.com/kf/Ua26a9ebfe30847ff8d4d7d7c7647c61cH.jpg"></a>
        <a class="title" href="/">
            <div class="main">惊蛰</div>
            <div class="sub normal cap"></div>
            <div class="sub hover cap" style="opacity:0">jingzhe.xyz</div>
        </a>
    </div>
    <nav class="menu dis-select">
        <a class="nav-item " href="/">博客</a>
        <a class="nav-item " href="/archives/">归档</a>
        <a class="nav-item " href="/about/">关于</a>
    </nav>
</header>
<script>
    $(function () {
        // https://v1.hitokoto.cn/?c=f&encode=text&max_length=8
        $.ajax({
            url: "https://v1.hitokoto.cn/?c=f&encode=text&max_length=10&min_length=5&c=i",
            success: function (result) {
                $(".normal").html(result);
            }
        });

    })
</script>
<div class="widgets">
    <div class="widget-wrap">
    <div class="widget-header cap dis-select"><span class="name">目录</span></div>
    <div class="widget-body fs14 toc-body">
        <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E4%BA%8B%E6%83%85%E4%B8%BA%E4%BB%80%E4%B9%88%E5%8F%91%E7%94%9F%EF%BC%9F"><span class="toc-text">1.事情为什么发生？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E9%97%AE%E9%A2%98%E4%BA%A7%E7%94%9F"><span class="toc-text">2.问题产生</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E9%97%AE%E9%A2%98%E9%AA%8C%E8%AF%81"><span class="toc-text">3.问题验证</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E4%B8%BA%E4%BB%80%E4%B9%88"><span class="toc-text">4.为什么</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-End"><span class="toc-text">5.End</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%99%E9%97%AE%E9%A2%98%EF%BC%8C%E6%98%8E%E6%98%BE%E4%B8%8D%E6%98%AF%E5%90%8E%E7%AB%AF%E7%9A%84%E9%94%85%E3%80%82%E5%90%8E%E7%AB%AF%E4%BC%A0%E9%80%92%E4%BA%86%E6%AD%A3%E7%A1%AE%E7%9A%84%E6%95%B0%E6%8D%AE%E5%88%B0%E5%89%8D%E7%AB%AF%EF%BC%8C%E8%83%BD%E4%B8%8D%E8%83%BD%E5%A4%84%E7%90%86%E3%80%81%E5%A4%84%E7%90%86%E7%9A%84%E6%AD%A3%E7%A1%AE%E4%B8%8D%E6%AD%A3%E7%A1%AE%EF%BC%8C%E6%A0%B9%E6%9C%AC%E5%92%8C%E5%90%8E%E7%AB%AF%E4%B8%80%E7%82%B9%E5%85%B3%E7%B3%BB%E9%83%BD%E6%B2%A1%E6%9C%89"><span class="toc-text">这问题，明显不是后端的锅。后端传递了正确的数据到前端，能不能处理、处理的正确不正确，根本和后端一点关系都没有</span></a>
    </div>

    <!-- posts/625de086.html
    
        <section>
            <h2>Related posts</h2>
            <ul>
            
                
                
                    <li><a href="/posts/625de086.html">/posts/625de086.html</a></li>
                
            
            </ul>
        </section>
     -->
</div>

<script>
    // 让锚点位置下降80个点数
    $(".body-main-content *[id]").each(i => {
        $($(".body-main-content *[id]")[i]).attr('style', 'padding-top: 60px;margin-top: -60px;');
    })

    $(function () {
        $('.toc-link').click(function () {
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location
                .hostname == this.hostname) {
                var $target = $(this);
                $target = $('[id=' + decodeURI(this.hash.slice(1)) + ']');
                if ($target.length) {
                    var targetOffset = $target.offset().top;
                    $('html,body').animate({
                            scrollTop: targetOffset
                        },
                        700);
                    return false;
                }
            }
        });
    })
</script>
    <footer class="footer dis-select">
    <div class="social-wrap">
        <a class="social" title="GitHub" href="https://github.com/xaoxuu" target="_blank"
            rel="external nofollow noopener noreferrer"><img class="lazy entered loaded"
                src="https://cdn.jsdelivr.net/gh/cdn-x/placeholder@1.0.3/social/08a41b181ce68.svg"
                data-src="https://cdn.jsdelivr.net/gh/cdn-x/placeholder@1.0.3/social/08a41b181ce68.svg"
                data-ll-status="loaded"></a><a class="social" title="Spotify"
            href="https://open.spotify.com/user/xaoxuu" target="_blank"
            rel="external nofollow noopener noreferrer"><img class="lazy entered loaded"
                src="https://cdn.jsdelivr.net/gh/cdn-x/placeholder@1.0.3/social/3845874.svg"
                data-src="https://cdn.jsdelivr.net/gh/cdn-x/placeholder@1.0.3/social/3845874.svg"
                data-ll-status="loaded"></a><a class="social" title="Unsplash"
            href="https://unsplash.com/@xaoxuu" target="_blank"
            rel="external nofollow noopener noreferrer"><img class="lazy entered loaded"
                src="https://cdn.jsdelivr.net/gh/cdn-x/placeholder@1.0.3/social/3616429.svg"
                data-src="https://cdn.jsdelivr.net/gh/cdn-x/placeholder@1.0.3/social/3616429.svg"
                data-ll-status="loaded"></a><a class="social" title="Comments" href="/about/#comments"
            rel="noopener noreferrer"><img class="lazy entered loaded"
                src="https://cdn.jsdelivr.net/gh/cdn-x/placeholder@1.0.3/social/942ebbf1a4b91.svg"
                data-src="https://cdn.jsdelivr.net/gh/cdn-x/placeholder@1.0.3/social/942ebbf1a4b91.svg"
                data-ll-status="loaded"></a></div>
</footer>
</div>
    </aside>
</div>

<style>

</style>
    <div class="loading-div" id="loading" style="display: none;">
    <div class="loading">
        <svg id="stage" viewBox="0 0 500 500" preserveAspectRatio="xMidYMid meet" stroke="#fff" stroke-width="3"
            stroke-linecap="round" fill="none"></svg>
        <span>加载中...</span>
    </div>
</div>
<style>
    .loading-div {
        position: absolute;
        display: flex;
        top: 0px;
        width: 100%;
        height: 100%;
        align-items: center;
        z-index: 20;
        animation-name: fadeIn;
        animation-duration: 2s;
        animation-fill-mode: forwards;
    }

    /*动画效果*/
    @keyframes fadeIn {
        from {
            backdrop-filter: blur(0px);
            background: rgba(0, 0, 0, 0);
        }

        to {
            backdrop-filter: blur(2px);
            background: rgb(0, 0, 0, 0.5);
        }
    }

    /*动画效果*/
    @keyframes fadeIn1 {
        from {
            filter: blur(1px);
        }

        to {
            filter: blur(0px);
        }
    }

    .loading {
        color: #fff;
        width: 250px;
        height: 250px;
        margin: 0 auto;
        display: flex;
        align-items: center;
        justify-content: center;
        align-content: center;
        flex-wrap: nowrap;
        flex-direction: column;
        animation-name: fadeIn1;
        animation-duration: 2s;
        animation-fill-mode: forwards;
    }

    svg {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
        /* background: #000; */
    }
</style>
<script src="https://lib.baomitu.com/gsap/3.7.1/gsap.min.js"></script>
<script>
    let pts = [],
        nPts = 12,
        lineLength = 60,
        timeScale = 0.5

    const radius = 180,
        tl = gsap.timeline()

    for (let i = 0; i < nPts; i++) { // plot points + add circles
        const c = document.createElementNS("http://www.w3.org/2000/svg", "circle"),
            angle = (i / nPts * Math.PI * 2) - Math.PI / 2,
            x = Math.cos(angle) * radius,
            y = Math.sin(angle) * radius

        pts.push(x.toFixed(2) + ',' + y.toFixed(2) + ' ')

        gsap.set(c, {
            x: 250,
            y: 250,
            scale: 0.8,
            attr: {
                class: 'c' + i,
                r: 3,
                cx: x,
                cy: y,
                fill: '#fff',
                stroke: 'none'
            }
        })

        stage.appendChild(c);
    }


    for (let i = 0; i <= nPts; i++) { // add paths + animate
        const p = document.createElementNS("http://www.w3.org/2000/svg", "path")

        gsap.set(p, {
            x: 250,
            y: 250,
            attr: {
                class: 'line' + i,
                d: 'M' + pts[i] + ' C' + gsap.utils.wrap(pts, [i + 2]) + ' ' + gsap.utils.wrap(pts, [i - 5]) +
                    ' ' + gsap.utils.wrap(pts, [i - 2]),
                // d:'M'+pts[i]+' c 0,0 '+gsap.utils.wrap(pts,[i-nPts/2])+' '+gsap.utils.wrap(pts,[i-3]),
                'stroke-dasharray': lineLength + ' ' + lineLength,
                'stroke-dashoffset': lineLength
            },
        });

        stage.appendChild(p);

        const lineTL = gsap.timeline({
                repeat: -1,
                defaults: {
                    duration: 0.4
                }
            })
            .to(p, {
                attr: {
                    'stroke-dashoffset': -lineLength
                },
                ease: 'expo.inOut',
                duration: 0.6
            }, 0.4)

        if (i < nPts) {
            lineTL.to('.c' + i, {
                scale: 1.2,
                ease: 'expo.inOut'
            }, 0.1)
            lineTL.to('.c' + i, {
                scale: 0.8,
                ease: 'expo.in'
            }, 0.5)
        }

        tl.add(lineTL, 1 - i / nPts);
    }

    tl.play(5).timeScale(timeScale)
</script>
<script>
    $(function () {
        // loadingShow()
    })

    function loadingShow() {
        $("#loading").show();
    }

    function loadingHide() {
        $("#loading").hide();
    }
</script>

    <!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery.scrollbar/0.2.9/jquery.scrollbar.min.js"></script> -->
    <script>
        // $(document).ready(function () {
        //     $('.l_body').scrollbar({
        //         barWidth: 10, //滚动条的宽度(这里根据需要写数值即可，不设置是10,即默认10px)
        //         position: "x,y", //写“x”代表只出水平滚动条，写“y”表示只出垂直滚动条，写“x,y”则出水平和垂直滚动条（只有在内容超出容器时才出现滚动条）
        //         wheelDis: 15 //滚轮滚动一次向下或向上滚动的距离，默认是15，可根据需要修改数值
        //     });
        // });
    </script>
    <script>
        $('img').lazyload({
            threshold: 0,
            failure_limit: 0,
            event: "scroll", //触发事件
            effect: "show", //显示方式
            container: window, //容器
            data_attribute: "original", //属性
            skip_invisible: true,
            appear: null,
            load: null,
            placeholder: ""
        });
    </script>
<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 3,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=o;var e=n.imageLazyLoadSetting.isSPA,i=n.imageLazyLoadSetting.preloadRatio||1,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function o(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight*i||document.documentElement.clientHeight*i)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},t.src!==i&&(n.src=i)}()}o(),n.addEventListener("scroll",function(){var t,e;t=o,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>